package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.mysql.cj.protocol.a.NativeConstants;

import java.lang.reflect.*;
import java.util.List;


public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);

        return (List<E>)list;
    }

    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if(objects.size() == 1){
            return (T)objects.get(0);
        }else{
            throw new RuntimeException("结果为null 或者数据过多");
        }
    }

    /**
     * 新增
     * @param statementid
     * @param params
     * @param <T>
     * @return
     * @throws Exception
     */
    @Override
    public <T> T insert(String statementid, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Object result= simpleExecutor.insert(configuration, mappedStatement, params);

        return (T)result;
    }

    /**
     * 修改
     * @param statementid
     * @param params
     * @param <T>
     * @return
     * @throws Exception
     */
    @Override
    public <T> T update(String statementid, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Object result= simpleExecutor.update(configuration, mappedStatement, params);

        return (T)result;
    }

    /**
     * 删除
     * @param statementid
     * @param params
     * @param <T>
     * @return
     * @throws Exception
     */
    @Override
    public <T> T delete(String statementid, Object... params) throws Exception {
        // 将要去完成对simpleExecutor里的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        Object result= simpleExecutor.delete(configuration, mappedStatement, params);

        return (T)result;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK 动态代理来为Dao 接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{
                mapperClass
        }, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                proxy：当前代理对象的应用
//                method：当前被调用方法的引用
//                args：传递的参数

                // 底层都还是执行JDK代码
                // 根据不同情况 调不同方法
                // 准备参数 ： statementid: sql语句唯一标识：namespace.id = 接口全限定名.方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId= className+"."+methodName;
                // 准备参数2 params：args
                // 获取被调用方法的返回类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断是否进行了 泛型类型参数化
                if(genericReturnType instanceof ParameterizedType){
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }else if("addUser".equals(methodName)){
                    Object result = insert(statementId,args);
                    return result;
                }else if("updateUser".equals(methodName)){
                    Object result = update(statementId,args);
                    return result;
                }else if("deleteUser".equals(methodName)){
                    Object result = delete(statementId,args);
                    return result;
                }
                return selectOne(statementId,args);
            }
        });
        return (T)proxyInstance;
    }
}
